package com.esperia09.webservice.mixibot.oauth;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import com.esperia09.webservice.mixibot.common.SendRequest;

/**
 * URLへデータをPOSTする関数
 * @author esperia
 *
 */
public class SendTokenRequest extends SendRequest {
	
	/**
	 * mixiからAccessToken/RefreshTokenを取得する
	 * @param authCode
	 * @return
	 * @throws IOException
	 */
	public static String getNewTokens(String authCode) throws IOException {
		if(authCode == null) {
			return null;
		}
		
		HttpURLConnection con = null;
		String result = "";
		try {
		    URL url = new URL(OAuthConstants.FOR_GET_TOKEN_URL);
		    con = (HttpURLConnection) url.openConnection();
		    con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
			
		    String postString = "grant_type=authorization_code"
		    	+ "&client_id=" + System.getProperty(OAuthConstants.MIXI_CONSUMER_KEY)
		    	+ "&client_secret=" + System.getProperty(OAuthConstants.MIXI_CONSUMER_SECRET)
		    	+ "&code=" + authCode // authorization code
		    	+ "&redirect_uri=" + OAuthConstants.OAUTH_AFTER_REDIRECT_URL;
		    
		    result = sendPost(con, postString);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return result;
	}

	/**
	 * Refresh Tokenを使ってAccessTokenを取得する
	 * @param authCode
	 * @return
	 * @throws IOException
	 */
	public static String refreshAccessToken(String refreshToken) throws IOException {
		if(refreshToken == null) {
			return null;
		}
		
		String result = "";
		HttpURLConnection con = null;
		try{
		    URL url = new URL(OAuthConstants.FOR_GET_TOKEN_URL);
		    con = (HttpURLConnection) url.openConnection();
		    con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
	
		    String postString = "grant_type=refresh_token"
		    	+ "&client_id=" + System.getProperty(OAuthConstants.MIXI_CONSUMER_KEY)
		    	+ "&client_secret=" + System.getProperty(OAuthConstants.MIXI_CONSUMER_SECRET)
		    	+ "&refresh_token=" + refreshToken;
		    
		    result = sendPost(con, postString);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		    if (con != null) con.disconnect();
		}
		
		return result;
	}
}
